package com.luoguijia.disk.login.service.impl;

import com.luoguijia.disk.login.entity.MenuLeveEntity;
import com.luoguijia.disk.login.entity.UserEntity;
import com.luoguijia.disk.login.repository.LoginDao;
import com.luoguijia.disk.login.service.LoginService;
import com.luoguijia.disk.login.uitl.DataUtil;
import com.luoguijia.disk.mybatis.entity.PtMenuEntity;
import com.luoguijia.disk.spring.util.MailUtil;
import com.luoguijia.disk.mybatis.entity.PtUserEntity;
import com.luoguijia.disk.spring.annotation.LogPoint;
import com.luoguijia.disk.spring.security.UserDiskEntity;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginDao loginDao;

    @Resource
    private HttpSession session;

    @Resource
    private MailUtil mailUtil;

    @Resource
    private PasswordEncoder passwordEncoder;

    // 原有方法保持不变...
    @LogPoint
    @Override
    public PtUserEntity queryUserInfoByName(String username) {
        return loginDao.queryUserInfoByName(username);
    }

    @Override
    public List<PtMenuEntity> queryMenuList() {
        String lang = LocaleContextHolder.getLocale().toString();
        UserDiskEntity userDiskEntity = (UserDiskEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        String userUnid = userDiskEntity.getUserUuid();

        return loginDao.queryMenuList(lang, userUnid);
    }

    @Override
    public List<MenuLeveEntity> queryMenuListLevel() {
        String lang = LocaleContextHolder.getLocale().toString();
        UserDiskEntity userDiskEntity = (UserDiskEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        String userUnid = userDiskEntity.getUserUuid();

        List<PtMenuEntity> ptMenuEntityList = loginDao.queryMenuList(lang, userUnid);

        List<MenuLeveEntity> leveEntityList = new ArrayList<>();
        for (PtMenuEntity ptMenuEntity : ptMenuEntityList) {
            leveEntityList.add(new MenuLeveEntity(ptMenuEntity));
        }

        List<MenuLeveEntity> sysEntityList = new ArrayList<>();
        boolean findFlag;
        for (MenuLeveEntity level1 : leveEntityList) {
            findFlag = false;
            for (MenuLeveEntity parent : leveEntityList) {
                if (parent.getMenuId().equals(level1.getParentId())) {
                    findFlag = true;
                    parent.addChild(level1);
                    break;
                }
            }
            if (!findFlag) {
                sysEntityList.add(level1);
            }
        }

        return sysEntityList;
    }

    @Override
    public List<String> queryPermissionList(String userUuid) {
        return loginDao.queryPermissionList(userUuid);
    }

    @Override
    @Transactional
    public void updatePassword(String userUuid, String newPassword) {
        String encodedPassword = passwordEncoder.encode(newPassword);
        loginDao.updatePassword(userUuid, encodedPassword);
    }

    @Override
    @Transactional
    public void batchResetPassword(List<Long> userIds) {
        String defaultEncodedPassword = passwordEncoder.encode("123456");
        loginDao.batchResetPassword(userIds, defaultEncodedPassword);
    }

    @Override
    @Transactional
    public void resetPassword(Long userId) {
        String defaultEncodedPassword = passwordEncoder.encode("123456");
        loginDao.resetPassword(userId, defaultEncodedPassword);
    }

    @Override
    public String sendVerificationCode(String phone) {
        return null;
    }

    @Override
    public String sendVerificationCodeByEmail(String email) {
        String code = String.format("%06d", (int) (Math.random() * 999999));
        boolean sendResult = mailUtil.sendVerificationCode(email, code);
        if (sendResult) {
            session.setAttribute("EMAIL_VERIFICATION_CODE_" + email, code);
            session.setAttribute("EMAIL_VERIFICATION_TIME_" + email, System.currentTimeMillis());
            return code;
        } else {
            return null;
        }
    }

    @Override
    public boolean verifyEmailCode(String email, String code) {
        String storedCode = (String) session.getAttribute("EMAIL_VERIFICATION_CODE_" + email);
        Long storedTime = (Long) session.getAttribute("EMAIL_VERIFICATION_TIME_" + email);

        if (storedCode == null || storedTime == null) {
            return false;
        }

        if (storedCode.equals(code) &&
                (System.currentTimeMillis() - storedTime) < 5 * 60 * 1000) {
            session.removeAttribute("EMAIL_VERIFICATION_CODE_" + email);
            session.removeAttribute("EMAIL_VERIFICATION_TIME_" + email);
            return true;
        }

        return false;
    }

    @Override
    @Transactional
    public boolean registerUser(UserEntity user, String verificationCode) {
        try {
            String sessionCode = (String) session.getAttribute("REGISTRY_VERIFY_CODE");
            if (sessionCode == null || !sessionCode.equalsIgnoreCase(verificationCode)) {
                System.out.println("验证码错误: 输入=" + verificationCode + ", 正确=" + sessionCode);
                return false;
            }
            session.removeAttribute("REGISTRY_VERIFY_CODE");

            String encodedPassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(encodedPassword);

            int result = loginDao.saveUser(user);
            System.out.println("注册结果: " + (result > 0 ? "成功" : "失败"));
            return result > 0;
        } catch (Exception e) {
            System.out.println("注册异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public ResponseEntity<byte[]> getVerifyImag() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        headers.setCacheControl("no-store, no-cache, must-revalidate");

        try {
            String vfcCode = DataUtil.getVfcCode(4);
            session.setAttribute("SESSION_VERIFY_CODE", vfcCode);
            session.setAttribute("SESSION_VERIFY_CODE_EXPIRE", System.currentTimeMillis() + 5 * 60 * 1000);
            byte[] imageBytes = DataUtil.getVfcImg(vfcCode);
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new byte[0], headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public boolean verifyLogin(String username, String password) {
        PtUserEntity user = queryUserInfoByName(username);
        if (user == null) return false;
        return passwordEncoder.matches(password, user.getPassword());
    }

    // 新增：验证码校验方法
//    @Override
//    public String verifyCaptcha(String inputCode) {
//        // 1. 获取session中存储的验证码和过期时间
//        String storedCode = (String) session.getAttribute("SESSION_VERIFY_CODE");
//        Long expireTime = (Long) session.getAttribute("SESSION_VERIFY_CODE_EXPIRE");
//
//        // 2. 验证逻辑
//        if (storedCode == null || expireTime == null) {
//            return false; // 验证码未生成
//        }
//        if (expireTime < System.currentTimeMillis()) {
//            return false; // 验证码已过期
//        }
//        // 忽略大小写校验（用户输入可能大小写不一致）
//        if(storedCode.equalsIgnoreCase(inputCode)){
//
//        }
//    }
}
